<?php
	//this script is called right after session_start();

	if (!isset($_SESSION['userId']) || intval($_SESSION['userId']) > 0) {
		//try to autologin from the cookie
		if (isset($_COOKIE['remember']) && !empty($_COOKIE['remember'])) {
			list($email, $hash) = explode(':', $_COOKIE['remember']);

			//get constants
			include("inc.const.php");

			// connection settings stored in file
			include("connectionParameters.php");

			$connection = mysql_connect($host,$user,$pass)
				or die ("Can't connect to server, try again later, please");

			//connect to this db
			mysql_select_db($database);

			//now validating username and password and status
			$sql = 'SELECT * FROM `Users`'
				. ' WHERE `email` ="' . mysql_real_escape_string($email) . '" AND `active` = 1 LIMIT 1';
			$result = mysql_query($sql);
			$row = mysql_fetch_array($result);
			if (mysql_num_rows($result) > 0) {
				if (md5($row['password'] . COOKIE_PASS . $row['email']) == $hash) {//can login user
					//now set the session from here if needed
					foreach ($row as $key => $value) {
						$_SESSION[$key] = $value;
					}
				} else {//validation failed -> delete cookie
					// set the expiration date to one hour ago
					setcookie ('remember', '', time() - 3600);
				}
			}

		}
	}
?>